package cz.kfad.ofrss.rss;


import android.content.Context;
import cz.kfad.ofrss.backend.BackendService;
import cz.kfad.ofrss.backend.IBackend;
import cz.kfad.ofrss.model.Category;
import cz.kfad.ofrss.model.RssFeed;

import java.util.LinkedList;
import java.util.List;

public class CategoriesScanner {

    private final List<Category> categories;
    private final List<RssFeed> feeds;

    public CategoriesScanner(Context initContext) {
        final IBackend backend = BackendService.createBackend(initContext);
        categories = backend.findAllCategories();
        feeds = backend.findFeeds();
    }

    public List<Category> findCategories(final RssFeed rssFeed) {
        final List<Category> result = new LinkedList<Category>();
        for (final Category category : categories) {
            if (passCategoryAndFeed(rssFeed, category)) {
                result.add(category);
            }
        }
        return result;
    }

    public List<RssFeed> findFeed(final Category category) {
        final List<RssFeed> result = new LinkedList<RssFeed>();
        for (final RssFeed feed : feeds) {
            if (passCategoryAndFeed(feed, category)) {
                result.add(feed);
            }
        }
        return result;
    }

    private boolean passCategoryAndFeed(final RssFeed rssFeed, final Category category) {
        final String keyAttr = category.getKey();
        final String[] keys = keyAttr.split(" ");
        if (keys.length == 0) {
            return false;
        }
        for (final String key : keys) {
            if (!rssFeed.getText().toLowerCase().contains(key.toLowerCase())
                    && !rssFeed.getTitle().toLowerCase().contains(key.toLowerCase())) {
                return false;
            }
        }
        return true;
    }

}
